package cn.com.xf.web.controller;

import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.formula.functions.Roman;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.com.xf.common.AbstractBaseController;
import cn.com.xf.common.Constants;
import cn.com.xf.common.StringUtil;
import cn.com.xf.domain.TblCheckLeave;
import cn.com.xf.domain.TblCheckMend;
import cn.com.xf.domain.TsDict;
import cn.com.xf.service.CompanyService;
import cn.com.xf.service.LeaveService;
import cn.com.xf.utils.DateUtils;
import cn.com.xf.utils.encode.EncrypTool;
import cn.com.xf.web.PageModel;
import cn.com.xf.web.form.LeaveForm;
import cn.com.xf.web.form.MendForm;
import cn.com.xf.web.security.UserInfo;

/**
 * 请假管理
 *
 */
@Controller
@RequestMapping("/check")
public class LeaveController extends AbstractBaseController {

	@Autowired
	private LeaveService leaveService;
	@Autowired
	private CompanyService companyService;
	
	@RequestMapping("/leaveList")
	public ModelAndView leaveList(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {
		ModelAndView mv = null;
		String year_month = StringUtil.StringFilter(form.getYear_month());
		String siteid = StringUtil.StringFilter(form.getSiteid());
		String userid = StringUtil.StringFilter(form.getUserid());
		String deptid = StringUtil.StringFilter(form.getDeptid());
		if(siteid.equals("") && deptid.equals("")) {
			mv = new ModelAndView("/check/leave_list", Constants.FORM_COMMAND_KEY, form);		
		}else {
			mv = new ModelAndView("/check/leave_dept_list", Constants.FORM_COMMAND_KEY, form);
		}		
		form.setYear_month(year_month);
		form.setSiteid(siteid);
		form.setUserid(userid);
		form.setDeptid(deptid!=null && deptid.equals("D999")?"":deptid);
		int count = leaveService.selectLeaveCount(year_month,userid, siteid, deptid!=null && deptid.equals("D999")?"":deptid);
		if (count == 0)
			return mv;
		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, PageModel.DEFAULT_PAGE_SIZE, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();
		List<TblCheckLeave> list = leaveService.selectLeave(begin, pageSize,year_month, userid, siteid, deptid!=null && deptid.equals("D999")?"":deptid);
		mv.addObject("list", list);
		return mv;
	}
	
	@RequestMapping("/addLeave")
	public ModelAndView addLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/add_leave", Constants.FORM_COMMAND_KEY, form);		
		return mv;
	}

	@RequestMapping("/doAddLeave")
	public ModelAndView doAddLeave(HttpServletRequest request, HttpServletResponse response, @Valid LeaveForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/check/add_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if(form.getStartDate() != null && form.getStartDate().equals("")) {
			FieldError e = new FieldError("", "startDate", "开始日期不能为空");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if(form.getEndDate() != null && form.getEndDate().equals("")) {
			FieldError e = new FieldError("", "endDate", "结束日期不能为空");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if(form.getReason() != null && form.getReason().equals("")) {
			FieldError e = new FieldError("", "reason", "请假原因不能为空");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if (form.isEndDateBeforeStartDate()) {
			FieldError e = new FieldError("", "endDate", "结束日期不能在开始日期之前");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		TblCheckLeave leave = new TblCheckLeave();
		leave.setUserid(form.getUserid());
		leave.setSiteid(form.getSiteid());
		leave.setStartdate(sdf.parse(form.getStartDate()));
		leave.setEnddate(sdf.parse(form.getEndDate()));
		leave.setType(form.getType());
		leave.setReason(form.getReason());
		leave.setAddtime(new Date());
		leave.setFlag(0);
		leave.setDeptflag(0);
		leave.setPersonflag(4);
		leaveService.insertLeave(leave);
		mv.addObject("status", "SUCCESS");
		return mv;
	}
	
	@RequestMapping("/editLeave")
	public ModelAndView editLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/edit_leave", Constants.FORM_COMMAND_KEY, form);
		Long id = new Long(form.getId());
		TblCheckLeave leave = leaveService.selectLeaveById(id);
		mv.addObject("leave", leave);
		return mv;
	}
	
	@RequestMapping("/doEditLeave")
	public ModelAndView doEditLeave(HttpServletRequest request, HttpServletResponse response, @Valid LeaveForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/check/add_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if(form.getStartDate() != null && form.getStartDate().equals("")) {
			FieldError e = new FieldError("", "startDate", "开始日期不能为空");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if(form.getEndDate() != null && form.getEndDate().equals("")) {
			FieldError e = new FieldError("", "endDate", "结束日期不能为空");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if(form.getReason() != null && form.getReason().equals("")) {
			FieldError e = new FieldError("", "reason", "请假原因不能为空");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		// 判断结束日期是否在开始日期之后
		if (form.isEndDateBeforeStartDate()) {
			FieldError e = new FieldError("", "endDate", "结束日期不能在开始日期之前");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		TblCheckLeave leave = new TblCheckLeave();		
		leave.setId(new Long(form.getId()));
		leave.setUserid(form.getUserid());
		leave.setSiteid(form.getSiteid());
		leave.setStartdate(sdf.parse(form.getStartDate()));
		leave.setEnddate(sdf.parse(form.getEndDate()));
		leave.setType(form.getType());
		leave.setReason(form.getReason());
		leave.setDeptflag(0);
		leaveService.updateUserleave(leave);
		mv.addObject("status", "SUCCESS");
		return mv;		
	}
	
	@RequestMapping("/editPersonLeave")
	public ModelAndView editPersonLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/edit_leave", Constants.FORM_COMMAND_KEY, form);
		Long id = new Long(form.getId());
		TblCheckLeave leave = leaveService.selectLeaveById(id);
		mv.addObject("leave", leave);
		mv.addObject("destroy",4);
		return mv;
	}
	
	@RequestMapping("/doEditPersonLeave")
	public ModelAndView doEditPersonLeave(HttpServletRequest request, HttpServletResponse response, @Valid LeaveForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/check/add_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if(form.getStartDate() != null && form.getStartDate().equals("")) {
			FieldError e = new FieldError("", "startDate", "开始日期不能为空");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if(form.getEndDate() != null && form.getEndDate().equals("")) {
			FieldError e = new FieldError("", "endDate", "结束日期不能为空");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		if(form.getReason() != null && form.getReason().equals("")) {
			FieldError e = new FieldError("", "reason", "请假原因不能为空");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		// 判断结束日期是否在开始日期之后
		if (form.isEndDateBeforeStartDate()) {
			FieldError e = new FieldError("", "endDate", "结束日期不能在开始日期之前");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		String personuser = ((UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getName();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		TblCheckLeave leave = new TblCheckLeave();		
		leave.setId(new Long(form.getId()));
		leave.setUserid(form.getUserid());
		leave.setSiteid(form.getSiteid());
		leave.setStartdate(sdf.parse(form.getStartDate()));
		leave.setEnddate(sdf.parse(form.getEndDate()));
		leave.setType(form.getType());
		leave.setReason(form.getReason());
		leave.setPersonuser(personuser);
		leaveService.updateUserleave(leave);
		mv.addObject("status", "SUCCESS");
		return mv;		
	}
	
	@RequestMapping("/deleteLeave")
	@ResponseBody
	public Map<String, Object> deleteLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {		
		int result = leaveService.deleteLeave(new Long(form.getId()));
		Map<String, Object> map = new HashMap<String, Object>();
		if (result < 1) {
			map.put("status", "FAILD");
		} else {
			map.put("status", "SUCCESS");
		}
		return map;
	}
	

	@RequestMapping("/auditDeptLeave")
	@ResponseBody
	public Map<String, Object> auditDeptLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {		
		Map<String, Object> map = new HashMap<String, Object>();
		TblCheckLeave leave = new TblCheckLeave();		
		leave.setId(new Long(form.getId()));
		leave.setDeptflag(2);
		leave.setDeptuser(form.getDeptuser());
		leaveService.updateUserleave(leave);
		map.put("status", "SUCCESS");		
		return map;
	}
	
	@RequestMapping("/auditPersonLeave")
	@ResponseBody
	public Map<String, Object> auditPersonLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {		
		Map<String, Object> map = new HashMap<String, Object>();
		String personuser = ((UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getName();
		TblCheckLeave leave = new TblCheckLeave();		
		leave.setId(new Long(form.getId()));
		leave.setPersonflag(Integer.valueOf(form.getPersonflag()));
		leave.setPersonuser(personuser);
		leaveService.updateUserleave(leave);
		map.put("status", "SUCCESS");		
		return map;
	}
	
	@RequestMapping("/deptDestroyLeave")
	@ResponseBody
	public Map<String, Object> deptDestroyLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {		
		Map<String, Object> map = new HashMap<String, Object>();
		TblCheckLeave leave = new TblCheckLeave();		
		leave.setId(new Long(form.getId()));
		leave.setDeptflag(3);
		leave.setDeptuser(form.getDeptuser());
		leaveService.updateUserleave(leave);
		map.put("status", "SUCCESS");		
		return map;
	}
	
	@RequestMapping("/userDelLeave")
	@ResponseBody
	public Map<String, Object> userDelLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {		
		Map<String, Object> map = new HashMap<String, Object>();
		TblCheckLeave leave = new TblCheckLeave();		
		leave.setId(new Long(form.getId()));
		leave.setFlag(1);
		leaveService.updateUserleave(leave);
		map.put("status", "SUCCESS");		
		return map;
	}
	
	@RequestMapping("/deptDelLeave")
	@ResponseBody
	public Map<String, Object> deptDelLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {		
		Map<String, Object> map = new HashMap<String, Object>();
		TblCheckLeave leave = new TblCheckLeave();		
		leave.setId(new Long(form.getId()));
		leave.setDeptflag(0);
		leaveService.updateUserleave(leave);
		map.put("status", "SUCCESS");		
		return map;
	}
	
	@RequestMapping("/personDestroyLeave")
	@ResponseBody
	public Map<String, Object> personDestroyLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {		
		Map<String, Object> map = new HashMap<String, Object>();
		TblCheckLeave leave = new TblCheckLeave();	
		String personuser = ((UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getName();
		leave.setId(new Long(form.getId()));
		leave.setPersonflag(3);
		leave.setPersonuser(personuser);
		leaveService.updateUserleave(leave);
		map.put("status", "SUCCESS");		
		return map;
	}
	
	@RequestMapping("/noDeptLeave")
	public ModelAndView noDeptLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/edit_leave", Constants.FORM_COMMAND_KEY, form);
		Long id = new Long(form.getId());
		TblCheckLeave leave = leaveService.selectLeaveById(id);
		mv.addObject("leave", leave);
		mv.addObject("destroy",2);
		return mv;
	}
	
	@RequestMapping("/doNoDeptLeave")
	public ModelAndView doNoDeptLeave(HttpServletRequest request, HttpServletResponse response, @Valid LeaveForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/check/add_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		
		if(form.getDeptremark() != null && form.getDeptremark().equals("")) {
			FieldError e = new FieldError("", "deptremark", "不通过原因不能为空");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}		
		TblCheckLeave leave = new TblCheckLeave();		
		leave.setId(new Long(form.getId()));		
		leave.setDeptflag(new Integer(form.getDeptflag()));
		leave.setDeptremark(form.getDeptremark());
		leave.setDeptuser(form.getDeptuser());
		leaveService.updateUserleave(leave);
		mv.addObject("status", "SUCCESS");
		return mv;		
	}
	
	@RequestMapping("/noPersonLeave")
	public ModelAndView noPersonLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/edit_leave", Constants.FORM_COMMAND_KEY, form);
		Long id = new Long(form.getId());
		TblCheckLeave leave = leaveService.selectLeaveById(id);
		mv.addObject("leave", leave);
		mv.addObject("destroy",3);
		return mv;
	}
	
	@RequestMapping("/doNoPersonLeave")
	public ModelAndView noPersonLeave(HttpServletRequest request, HttpServletResponse response, @Valid LeaveForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/check/add_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		
		if(form.getPersonremark() != null && form.getPersonremark().equals("")) {
			FieldError e = new FieldError("", "deptremark", "不通过原因不能为空");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}		
		TblCheckLeave leave = new TblCheckLeave();		
		leave.setId(new Long(form.getId()));		
		leave.setPersonflag(new Integer(form.getPersonflag()));
		leave.setPersonremark(form.getPersonremark());
		leave.setPersonuser(form.getPersonuser());
		leaveService.updateUserleave(leave);
		mv.addObject("status", "SUCCESS");
		return mv;		
	}
	
	@RequestMapping("/userDestroyLeave")
	public ModelAndView userDestroyLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/edit_leave", Constants.FORM_COMMAND_KEY, form);
		Long id = new Long(form.getId());
		TblCheckLeave leave = leaveService.selectLeaveById(id);
		mv.addObject("leave", leave);
		mv.addObject("destroy",1);
		return mv;
	}
	
	@RequestMapping("/doUserDestroyLeave")
	public ModelAndView doUserDestroyLeave(HttpServletRequest request, HttpServletResponse response, @Valid LeaveForm form,
			BindingResult result) throws Exception {
		ModelAndView mv = new ModelAndView("/check/add_result", Constants.FORM_COMMAND_KEY, form);
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}
		
		if(form.getRemark() != null && form.getRemark().equals("")) {
			FieldError e = new FieldError("", "remark", "销毁原因不能为空");
			errorList = new ArrayList<ObjectError>();
			errorList.add(e);
			String errorJson = errorToJson(errorList);
			mv.addObject("errorJson", errorJson);
			return mv;
		}		
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		TblCheckLeave leave = new TblCheckLeave();		
		leave.setId(new Long(form.getId()));		
		leave.setAddtime(new Date());
		leave.setFlag(new Integer(form.getFlag()));
		leave.setRemark(form.getRemark());
		leaveService.updateUserleave(leave);
		mv.addObject("status", "SUCCESS");
		return mv;		
	}
	@RequestMapping("/leavePersonList")
	public ModelAndView leavePersonList(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/leave_person_list", Constants.FORM_COMMAND_KEY, form);
		String year_month = StringUtil.StringFilter(form.getYear_month());
		String siteid = StringUtil.StringFilter(form.getSiteid());
		String userid = StringUtil.StringFilter(form.getUserid());
		String deptid = StringUtil.StringFilter(form.getDeptid());
		if (siteid.equals("") || !isSiteId(siteid)) {
			siteid = getDefaultSiteid();
		}
		form.setYear_month(year_month);
		form.setSiteid(siteid);
		form.setUserid(userid);
		form.setDeptid(deptid!=null && deptid.equals("D999")?"":deptid);
		int count = leaveService.selectPersonLeaveCount(year_month,userid, siteid, deptid!=null && deptid.equals("D999")?"":deptid);
		if (count == 0)
			return mv;

		int pageNum = 1;
		if (StringUtils.isNotBlank(form.getPageNum())) {
			pageNum = Integer.valueOf(form.getPageNum());
		}
		PageModel pageModel = new PageModel(count, 20, pageNum, form);
		int begin = pageModel.getBegin();
		int pageSize = pageModel.getPageSize();
		List<TblCheckLeave> list = leaveService.selectPersonLeave(begin, pageSize,year_month, userid, siteid, deptid!=null && deptid.equals("D999")?"":deptid);
		Map<String, Object> map = companyService.getDetps();
		for (TblCheckLeave leave: list) {
			if (leave.getDeptid() == null) {
				leave.setDeptname("");
			} else {
				leave.setDeptname(map.get(leave.getDeptid())+"");
			}
		}
		mv.addObject("list", list);
		return mv;
	}

	@RequestMapping("/addPersonLeave")
	public ModelAndView addPersonLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {
		ModelAndView mv = new ModelAndView("/check/add_person_leave", Constants.FORM_COMMAND_KEY, form);
		mv.addObject("defaultSiteid", getDefaultSiteid());
		return mv;
	}

	@RequestMapping("/doAddPersonLeave")
	@ResponseBody
	public Map<String, Object> doAddPersonLeave(HttpServletRequest request, HttpServletResponse response, @Valid LeaveForm form,
			BindingResult result) throws Exception {
		Map<String, Object> map = new HashMap<String, Object>();
		List<ObjectError> errorList = null;
		if (result.hasErrors()) {
			errorList = result.getAllErrors();
			String errorJson = errorToJson(errorList);
			map.put("errorJson", errorJson);
			return map;
		}
		String personuser = ((UserInfo)SecurityContextHolder.getContext().getAuthentication().getPrincipal()).getName();
		String  leaveJson = form.getLeaveJson();
		JSONParser jp = new JSONParser();
		JSONArray formJson = (JSONArray) jp.parse(leaveJson);
		List<LeaveForm> leaveList = new ArrayList<LeaveForm>();
		for (int i = 0; i < formJson.size(); i++) {
			JSONObject jons = (JSONObject)formJson.get(i);
			LeaveForm lf = new LeaveForm();
			int rowIndex = i+1;
			lf.setPersonuser(personuser);
			if(!isSiteId(jons.get("siteid")+"")) {
				map.put("status", "FAILD");
				map.put("msg", "第&nbsp<font color='#FF0000'>"+rowIndex+"</font>&nbsp条记录所属公司不合法，请校对后单独添加！");
				return map;
			}
			lf.setSiteid(jons.get("siteid")+"");
			lf.setUserid(jons.get("userid")+"");
			lf.setStartDate(jons.get("startDate")+":00");
			lf.setEndDate(jons.get("endDate")+":00");
			lf.setType(jons.get("type")+"");
			lf.setReason(jons.get("reason")+"");
			lf.setFlag(2);
			lf.setDeptflag(2);
			lf.setPersonflag(0);
			// 判断结束日期是否在开始日期之后
			if (lf.isEndDateBeforeStartDate()) {
				map.put("status", "FAILD");
				map.put("msg", "第&nbsp<font color='#FF0000'>"+rowIndex+"</font>&nbsp条记录开始日期在结束日期之后！");
				return map;				
			}
			leaveList.add(lf);
			
			
		}
		for (LeaveForm leaveForm : leaveList) {
			// 添加
			if (!leaveForm.getUserid().contains(",")) {
				TblCheckLeave leave = leaveForm.copyTo();
				leaveService.insertLeave(leave);
			} else {
				TblCheckLeave leave = leaveForm.copyTo();
				String[] userids = leaveForm.getUserid().split(",");
				for (String userid: userids) {
					leave.setUserid(userid);
					leaveService.insertLeave(leave);
				}
			}
		}		
		map.put("status", "SUCCESS");
		return map;
	}
	
	@RequestMapping("/exportLeave")
	public void exportLeave(HttpServletRequest request, HttpServletResponse response, LeaveForm form)
			throws Exception {
		String siteid = form.getSiteid();
		String deptid = StringUtil.StringFilter(form.getDeptid()!=null && form.getDeptid().equals("D999")?"":form.getDeptid());
		String sitename = form.getSitename();
		String year_Month = StringUtil.StringFilter(form.getYear_month());
		String userid=StringUtil.StringFilter(form.getUserid());;
		List<TblCheckLeave> list = leaveService.selectExport(year_Month, siteid, deptid,userid);
		String sheetName = year_Month.replaceAll("-", "年")+"月"+sitename+deptid+"请假记录";
		String[] title= {"所属公司","部门","工号","姓名","请假开始日期","请假结束日期","请假原因","操作人","操作时间"};
		// 1.创建一个workbook，对应一个Excel文件
		HSSFWorkbook wb = new HSSFWorkbook();
	    // 2.在workbook中添加一个sheet，对应Excel中的一个sheet
	    HSSFSheet sheet = wb.createSheet(sheetName);
	    // 3.在sheet中添加表头第0行，老版本poi对excel行数列数有限制short
	    sheet.createFreezePane( 0, 1, 0, 1 );
	    HSSFRow row = sheet.createRow((int) 0);
	    // 4.创建单元格，设置值表头，设置表头居中
	    HSSFCellStyle style = wb.createCellStyle();
	    // 居中格式
	    style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
	    for (int i = 0; i < title.length; i++) {    
            HSSFCell cell = row.createCell(i);    
            cell.setCellValue(title[i]);    
            cell.setCellStyle(style);    
            sheet.setColumnWidth(i, 6*2*256);
        }
	    for (int i = 0; i < list.size(); i++) {    
            row = sheet.createRow(i + 1);    
            TblCheckLeave leave = list.get(i); 
            row.createCell(0).setCellValue(leave.getSitename());
            row.createCell(1).setCellValue(leave.getDeptname()!=null?leave.getDeptname():"");    
            row.createCell(2).setCellValue(leave.getUserid());
            row.createCell(3).setCellValue(leave.getUsername());    
            row.createCell(4).setCellValue(DateUtils.formatDatetime(leave.getStartdate()));
            row.createCell(5).setCellValue(DateUtils.formatDatetime(leave.getEnddate()));
            row.createCell(6).setCellValue(leave.getReason());
            row.createCell(7).setCellValue(leave.getOperateUser());
            row.createCell(8).setCellValue(DateUtils.formatDatetime(leave.getOperateTime()));
        }
	    response.setContentType("application/vnd.ms-excel;charset=utf-8");
	    response.setHeader("Content-Disposition", "attachment;filename="
	            + new String((sheetName + ".xls").getBytes(), "iso-8859-1"));
	    OutputStream ouputStream = response.getOutputStream();    
        wb.write(ouputStream);    
        ouputStream.flush();    
        ouputStream.close();
	}

	
	
}
